package com.hlt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hlt.context.BaseContext;
import com.hlt.dto.FollowsPageQueryDTO;
import com.hlt.entity.Follows;
import com.hlt.entity.Users;
import com.hlt.mapper.FollowsMapper;
import com.hlt.mapper.UsersMapper;
import com.hlt.result.PageResult;
import com.hlt.service.IFollowsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hlt.config.UserStatsUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lzf
 * @since 2024-11-25
 */
@Service
public class FollowsServiceImpl extends ServiceImpl<FollowsMapper, Follows> implements IFollowsService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UserStatsUtils userStatsUtils;

    @Override
    @Transactional
    public void follow(Long followingId) {
        // 获取当前用户ID
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new IllegalArgumentException("请先登录");
        }

        // 参数校验
        Assert.notNull(followingId, "被关注用户ID不能为空");

        // 检查被关注用户是否存在
        Users followingUser = usersMapper.selectById(followingId);
        if (followingUser == null) {
            throw new IllegalArgumentException("被关注用户不存在");
        }

        // 不能关注自己
        if (userId.equals(followingId)) {
            throw new IllegalArgumentException("不能关注自己");
        }

        // 检查是否已关注
        LambdaQueryWrapper<Follows> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follows::getFollowerId, Math.toIntExact(userId))
                .eq(Follows::getFollowingId, followingId);
        if (count(queryWrapper) > 0) {
            throw new IllegalArgumentException("已经关注过该用户");
        }

        // 创建关注记录
        Follows follow = new Follows();
        follow.setFollowerId(Math.toIntExact(userId));
        follow.setFollowingId(Math.toIntExact(followingId));
        follow.setCreatedAt(LocalDateTime.now());

        // 保存关注记录
        save(follow);

        // 更新用户统计信息
        userStatsUtils.updateStats(Math.toIntExact(followingId), "followersCount", true);
        userStatsUtils.updateStats(Math.toIntExact(userId), "followingCount", true);
    }

    @Override
    @Transactional
    public void unfollow(Long followingId) {
        // 获取当前用户ID
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new IllegalArgumentException("请先登录");
        }

        // 查询关注记录
        LambdaQueryWrapper<Follows> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follows::getFollowerId, Math.toIntExact(userId))
                .eq(Follows::getFollowingId, followingId);
        Follows follow = getOne(queryWrapper);

        if (follow == null) {
            throw new IllegalArgumentException("关注记录不存在");
        }

        // 物理删除关注记录
        removeById(follow.getFollowId());

        // 更新用户统计信息
        userStatsUtils.updateStats(Math.toIntExact(userId), "followingCount", false);
        userStatsUtils.updateStats(Math.toIntExact(followingId), "followersCount", false);
    }

    @Override
    public PageResult getFollowingList(FollowsPageQueryDTO pageQueryDTO) {
        // 构建分页对象
        Page<Follows> page = new Page<>(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<Follows> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follows::getFollowerId, Math.toIntExact(pageQueryDTO.getUserId()))
                .orderByDesc(Follows::getCreatedAt);

        // 执行分页查询
        page = page(page, queryWrapper);

        return new PageResult(page.getTotal(), page.getRecords());
    }

    @Override
    public PageResult getFollowersList(FollowsPageQueryDTO pageQueryDTO) {
        // 构建分页对象
        Page<Follows> page = new Page<>(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<Follows> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follows::getFollowingId, Math.toIntExact(pageQueryDTO.getUserId()))
                .orderByDesc(Follows::getCreatedAt);

        // 执行分页查询
        page = page(page, queryWrapper);

        return new PageResult(page.getTotal(), page.getRecords());
    }

    @Override
    public PageResult getCurrentUserFollowingList(FollowsPageQueryDTO pageQueryDTO) {
        // 获取当前用户ID
        Long currentUserId = BaseContext.getCurrentId();
        if (currentUserId == null) {
            throw new IllegalArgumentException("请先登录");
        }

        // 设置当前用户ID
        pageQueryDTO.setUserId(currentUserId);

        // 调用获取关注列表的方法
        return getFollowingList(pageQueryDTO);
    }

    @Override
    public PageResult getCurrentUserFollowersList(FollowsPageQueryDTO pageQueryDTO) {
        // 获取当前用户ID
        Long currentUserId = BaseContext.getCurrentId();
        if (currentUserId == null) {
            throw new IllegalArgumentException("请先登录");
        }

        // 设置当前用户ID
        pageQueryDTO.setUserId(currentUserId);

        // 调用获取粉丝列表的方法
        return getFollowersList(pageQueryDTO);
    }
}
